<!-- 库房管理---备料计划 -->
<script lang="ts">
export default {
  name: "materialPlan"
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import { VxeTableInstance, VxeToolbarInstance } from "vxe-table";
import { getProcessAll } from "/@/api/basic/workprocedure";
import {
  queryMaterialPlanPage,
  addMaterialPlan
} from "/@/api/wms/materialPlan";
import { dateFormatYMD } from "/@/utils/date";
import { queryProductOrderPage } from "/@/api/prm/productionOder";
import { queryItemByCodes } from "/@/api/basic/dictionaries";
import { queryMaterialPage } from "/@/api/basic/material";
import { errorMessage, successMessage, alertMessage } from "/@/utils/message";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";
const route = useRoute();
const routeName = route.name as string;
const xTable = ref({} as VxeTableInstance);
const xToolbar = ref({} as VxeToolbarInstance);
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    date: "",
    prodOrderNo: "",
    deviceId: "",
    bomCode: "",
    bomName: "",
    showFlag: "备料",
    programNumber: ""
  }
});

// 查询
const searchEvent = () => {
  const data: any = {};
  Object.assign(data, table.listQuery);
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  if (table.listQuery.date) {
    data.cashingDateStart =
      dateFormatYMD(table.listQuery.date[0]) + " 00:00:00";
    data.cashingDateEnd = dateFormatYMD(table.listQuery.date[1]) + " 23:59:59";
  } else {
    data.cashingDateStart = "";
    data.cashingDateEnd = "";
  }
  delete data.date;
  table.loading = true;
  queryMaterialPlanPage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
//获取工序名称
const getProcess = () => {
  getProcessAll().then((res: any) => {
    if (res.code === 0) {
      procedure.processData = res.data;
    }
  });
};
// 分页查询所有的货品
const getAllWh = (target: any) => {
  var str = "" as string;
  if (target && target.target.value) {
    str = target.target.value;
  }
  const data: any = {};
  Object.assign(data, table.listQuery);
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  data.name = str;
  table.loading = true;
  queryMaterialPage(data).then((res: any) => {
    if (res.code === 0) {
      procedure.goodsData = res.data.list;
    }
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
// 添加
const procedure = reactive({
  loading: false,
  submitLoading: false,
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  processData: [] as any[],
  goodsData: [] as any[],
  numberData: [] as any[], //存储数量单位信息
  orderData: [] as any[],
  idsDo: {
    ids: []
  },
  formData: {
    bnoNo: "",
    cashingDate: "",
    prodOrderId: "",
    prodOrderNo: "",
    materialPlanItems: [] as any[],
    processStepId: ""
  },
  formRules: {
    prodOrderId: [
      { required: true, message: "请选择生产订单编号", trigger: "blur" }
    ],
    processStepId: [{ required: true, message: "请选择工序", trigger: "blur" }]
  },
  disabledDate: function (time) {
    return time.getTime() + 8.64e7 < Date.now(); //今天之前的日期禁用（不包括今天）
  },
  picking: [
    { label: "是", value: 1 },
    { label: "否", value: 0 }
  ]
});

const addRepair = () => {
  procedure.formData.materialPlanItems.push({
    bomCode: "",
    useNum: 0,
    id: 0,
    materialPlanId: 0,
    bomId: "",
    lengthUnit: "",
    longt: "",
    miscellaneousDeliveryId: 0,
    quantityUnit: "",
    measureUnit: "",
    remark: "",
    reqNum: 0,
    specification: "",
    thickness: "",
    thicknessUnit: "",
    weight: "",
    weightUnit: "",
    node: "",
    width: "",
    widthUnit: ""
  });
};
// 领料
const insertEvent = () => {
  procedure.selectRow = null;
  procedure.showEdit = true;
  procedure.formData.cashingDate = dateFormatYMD(new Date()) + " 00:00:00";
  addRepair();
  queryUnit("数量");
};
// 删除
const dele = i => {
  procedure.formData.materialPlanItems.splice(i, 1);
};
// 名称改变时的变化
const proOrderChange = () => {
  if (procedure.formData.prodOrderId) {
    var arr = procedure.orderData.filter(
      item => item.id == procedure.formData.prodOrderId
    )[0];
    procedure.formData.bnoNo = arr.bnoNo;
    procedure.formData.prodOrderNo = arr.prodOrderNo;
  } else {
    procedure.formData.bnoNo = "";
    procedure.formData.prodOrderNo = "";
  }
};
// 名称改变时的变化
const codeChange = (id, i) => {
  if (id) {
    var arr = procedure.goodsData.filter(item => item.id == id)[0];
    var data = procedure.formData.materialPlanItems[i];
    Object.keys(data).forEach(key => {
      data[key] = arr[key] ? arr[key] : data[key];
    });
    data.bomCode = arr.code;
    data.name = arr.name;
    data.thicknessUnit = arr.thicknessUnitCN;
    data.weightUnit = arr.weightUnitCN;
    data.widthUnit = arr.widthUnitCN;
    data.lengthUnit = arr.lengthUnitCN;
    console.log(arr, data);
  } else {
    procedure.formData.materialPlanItems[i] = {
      bomCode: "",
      useNum: 0,
      id: 0,
      materialPlanId: 0,
      bomId: "",
      lengthUnit: "",
      longt: "",
      miscellaneousDeliveryId: 0,
      quantityUnit: "",
      measureUnit: "",
      remark: "",
      reqNum: 0,
      specification: "",
      thickness: "",
      thicknessUnit: "",
      weight: "",
      weightUnit: "",
      node: "",
      width: "",
      widthUnit: ""
    };
  }
};

// 分页查询所有的货品
const getAllProductOrder = (target: any) => {
  var str = "" as string;
  if (target && target.target.value) {
    str = target.target.value;
  }
  const data: any = {};
  Object.assign(data, table.listQuery);
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  data.prodOrderNo = str;
  queryProductOrderPage(data).then((res: any) => {
    if (res.code === 0) {
      procedure.orderData = res.data.list;
    }
  });
};
const checkRoleNameUnique = () => {
  var selectData = [];
  Object.keys(procedure.formData.materialPlanItems).forEach(key => {
    if (procedure.formData.materialPlanItems[key].name) {
      selectData.push(procedure.formData.materialPlanItems[key].name);
    }
  });
  if (new Set(selectData).size !== selectData.length) {
    alertMessage("当前有信息的编码或名称重复，请核对信息", "提示");
    return false;
  }
  return true;
};
// 入库表单提交
const insertForm = ref<InstanceType<typeof ElForm>>();

const submitEvent = () => {
  var bool = false;
  var bool1 = false;
  if (procedure.formData.materialPlanItems.length > 0) {
    for (var i = 0; i < procedure.formData.materialPlanItems.length; i++) {
      let data = procedure.formData.materialPlanItems[i];
      Object.keys(data).forEach(key => {
        if (key == "name" || key == "useNum") {
          data[key] === "" ? (bool = true) : null;
        }
        if (key == "useNum") {
          data[key] == 0 ? (bool1 = true) : null;
        }
      });
    }
    if (bool) {
      alertMessage("请将数据填写完整", "提示");
      return;
    }
    if (bool1) {
      alertMessage("备料数量不能为0", "提示");
      return;
    }
  } else {
    alertMessage("请填写详情信息", "提示");
    return;
  }
  if (!checkRoleNameUnique()) {
    return;
  }
  procedure.tableData = [];
  procedure.formData.materialPlanItems.map((item, index) => {
    procedure.tableData.push({
      bomCode: item.bomCode,
      cashingDate: procedure.formData.cashingDate,
      processStepId: procedure.formData.processStepId,
      prodOrderNo: procedure.formData.prodOrderNo,
      quantityUnit: item.quantityUnit,
      useNum: item.useNum
    });
  });
  insertForm.value.validate(valid => {
    if (valid) {
      procedure.submitLoading = true;
      // 新增
      addMaterialPlan(procedure.tableData)
        .then((res: any) => {
          if (res.code === 0) {
            handleClose();
            searchEvent();
            successMessage("新增成功");
          } else {
            procedure.submitLoading = false;
            errorMessage(res.message);
          }
        })
        .catch(() => {
          errorMessage("操作失败");
          procedure.submitLoading = false;
        });
    }
  });
};
const handleClose = () => {
  nextTick(() => {
    procedure.formData = {
      bnoNo: "",
      cashingDate: "",
      prodOrderId: "",
      prodOrderNo: "",
      materialPlanItems: [] as any[],
      processStepId: ""
    };
    procedure.submitLoading = false;
    procedure.showEdit = false;
  });
};
// 获取数量单位
const queryUnit = (code: any) => {
  queryItemByCodes([code]).then((res: any) => {
    procedure.numberData = res;
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    searchEvent();
    getProcess();
    getAllWh("");
    queryUnit("数量");
    const $table = xTable.value;
    const $toolbar = xToolbar.value;
    $table.connect($toolbar);
    table.tableHeight = changeHeight();
  });
});
</script>
<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="生产订单编号">
        <template #default="{ data }">
          <vxe-input
            v-model="data.prodOrderNo"
            placeholder="请输入生产订单编号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="程序号">
        <template #default="{ data }">
          <vxe-input
            v-model="data.programNumber"
            placeholder="请输入程序号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="设备/班组" field="deviceId" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.deviceId"
            placeholder="请输入设备/班组"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="料号" field="bomCode" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.bomCode"
            placeholder="请输入料号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="品名" field="bomName" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.bomName"
            placeholder="请输入品名"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="备料时间" field="date">
        <template #default="{ data }">
          <el-date-picker
            v-model="data.date"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          ></el-date-picker>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="searchEvent"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-toolbar ref="xToolbar" style="margin: 12px 0 -12px 0" custom>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column
        field="programNumber"
        title="程序号"
        min-width="300"
      ></vxe-column>
      <vxe-column
        field="prodOrderNo"
        title="生产订单编号"
        min-width="180"
      ></vxe-column>
      <vxe-column
        field="processStepName"
        title="工序名称"
        min-width="100"
      ></vxe-column>
      <vxe-column
        title="设备/班组"
        field="deviceId"
        min-width="200"
      ></vxe-column>
      <vxe-column field="cashingDate" title="备料时间" width="120">
        <template #default="{ row }">
          {{ row.cashingDate ? row.cashingDate.split(" ")[0] : "" }}
        </template>
      </vxe-column>
      <vxe-column field="bomName" title="品名" width="200">
        <template #default="{ row }">
          <span
            :style="{
              color:
                row?.programNumber && row?.bomName != row?.texture ? 'red' : ''
            }"
          >
            {{ row.bomName }}
          </span>
        </template>
      </vxe-column>
      <vxe-column field="texture" title="CAM材质" min-width="120">
        <template #default="{ row }">
          <span
            :style="{
              color:
                row?.programNumber && row?.bomName != row?.texture ? 'red' : ''
            }"
          >
            {{ row.texture }}
          </span>
        </template>
      </vxe-column>
      <vxe-column field="longt" title="长度(单位)" min-width="100">
        <template #default="{ row }">
          {{ row.longt
          }}{{
            row.longt && row.lengthUnitCN ? "(" + row.lengthUnitCN + ")" : ""
          }}
        </template>
      </vxe-column>
      <vxe-column field="width" title="宽度(单位)" min-width="100">
        <template #default="{ row }">
          {{ row.width
          }}{{
            row.width && row.widthUnitCN ? "(" + row.widthUnitCN + ")" : ""
          }}
        </template>
      </vxe-column>
      <vxe-column field="thickness" title="厚度/高度(单位)" min-width="140">
        <template #default="{ row }">
          {{ row.thickness
          }}{{
            row.thickness && row.thicknessUnitCN
              ? "(" + row.thicknessUnitCN + ")"
              : ""
          }}
        </template>
      </vxe-column>
      <vxe-column field="weight" title="成本(单位)" width="100">
        <template #default="{ row }">
          {{ row.weight
          }}{{
            row.weight && row.weightUnitCN ? "(" + row.weightUnitCN + ")" : ""
          }}
        </template>
      </vxe-column>
      <vxe-column title="备料数量(单位)" width="120">
        <template #default="{ row }">
          {{ row.useNum
          }}{{
            row.useNum && row.quantityUnit ? "(" + row.quantityUnit + ")" : ""
          }}
        </template>
      </vxe-column>
      <vxe-column field="bomCode" title="料号" min-width="130"></vxe-column>
      <vxe-column
        field="figureNumber"
        title="别名"
        min-width="150"
      ></vxe-column>
      <vxe-column field="modelNumber" title="机型" width="150"></vxe-column>
      <vxe-column field="bomType" title="财务分类" min-width="100"></vxe-column>
      <vxe-column
        field="itemCategory"
        title="库存分类"
        min-width="100"
      ></vxe-column>
      <vxe-column
        field="deliveryState"
        title="交货状态"
        min-width="100"
      ></vxe-column>
      <vxe-column
        field="modelAttributes"
        title="形态属性"
        min-width="100"
      ></vxe-column>
      <!-- <vxe-column field="productLine" title="产品系列" width="120"></vxe-column> -->
      <vxe-column field="measureUnit" title="计量单位" width="120"></vxe-column>
      <vxe-column
        field="assistMeasureUnit"
        title="辅计量单位"
        width="120"
      ></vxe-column>
      <vxe-column field="specification" title="规格" width="150"></vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 领料弹框 -->
    <el-dialog
      v-model="procedure.showEdit"
      title="新增&保存"
      top="7vh"
      width="80%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="insertForm"
        :model="procedure.formData"
        :rules="procedure.formRules"
        label-align="right"
        label-width="120px"
      >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item prop="prodOrderId" label="生产订单编号">
              <el-select
                v-model="procedure.formData.prodOrderId"
                filterable
                clearable
                placeholder="请选择"
                size="small"
                style="width: 100%"
                @keyup="getAllProductOrder"
                @clear="getAllProductOrder"
                @blur="getAllProductOrder"
                @focus="getAllProductOrder"
                @change="proOrderChange"
              >
                <el-option
                  v-for="item in procedure.orderData"
                  :key="item.id"
                  :label="item.prodOrderNo + '（' + item.bnoNo + '）'"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item prop="bnoNo" label="销售单号">
              <el-input
                v-model="procedure.formData.bnoNo"
                placeholder="请输入订单编号"
                size="small"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item prop="processStepId" label="工序名称">
              <el-select
                v-model="procedure.formData.processStepId"
                size="small"
                filterable
                placeholder="请选择工序"
                style="width: 100%"
                :disabled="procedure.selectRow ? true : false"
              >
                <el-option
                  v-for="item in procedure.processData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item prop="cashingDate" label="备料时间">
              <el-date-picker
                v-model="procedure.formData.cashingDate"
                type="date"
                size="small"
                style="width: 100%"
                :disabled-date="procedure.disabledDate"
                clearable
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button type="primary" size="small" @click="addRepair"
          >添加</el-button
        >
      </el-form>
      <el-table
        stripe
        :data="procedure.formData.materialPlanItems"
        border
        fit
        size="mini"
        highlight-current-row
        tooltip-effect="dark"
      >
        <el-table-column
          type="index"
          width="50"
          label="序号"
          fixed
        ></el-table-column>

        <el-table-column label="品名" min-width="300">
          <template #default="scope">
            <el-select
              v-model="scope.row.name"
              placeholder="请选择"
              style="width: 100%"
              size="small"
              @keyup="getAllWh"
              @clear="getAllWh"
              @change="codeChange(scope.row.name, scope.$index)"
            >
              <el-option
                v-for="item in procedure.goodsData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="bomCode"
          label="料号"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="measureUnit"
          label="计量单位"
          min-width="100"
        ></el-table-column>
        <el-table-column label="长度(单位)" width="90">
          <template #default="{ row }">
            {{ row.longt
            }}{{
              row.longt && row.lengthUnit ? "(" + row.lengthUnit + ")" : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="宽度(单位)" width="90">
          <template #default="{ row }">
            {{ row.width
            }}{{ row.width && row.widthUnit ? "(" + row.widthUnit + ")" : "" }}
          </template>
        </el-table-column>
        <el-table-column label="厚度/高度(单位)" width="110">
          <template #default="{ row }">
            {{ row.thickness
            }}{{
              row.thickness && row.thicknessUnit
                ? "(" + row.thicknessUnit + ")"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="规格"
          width="120"
          prop="specification"
        ></el-table-column>
        <el-table-column label="成本(单位)" width="80">
          <template #default="{ row }">
            {{ row.weight
            }}{{
              row.weight && row.weightUnit ? "(" + row.weightUnit + ")" : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="备料数量" prop="useNum" width="200">
          <template #default="scope">
            <el-input-number
              size="small"
              v-model="scope.row.useNum"
              :min="0"
              :precision="2"
              :step="0.1"
              placeholder="请输入领取数量"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量单位" width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.quantityUnit"
              filterable
              size="small"
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in procedure.numberData"
                :key="item.id"
                :label="item.unitName"
                :value="item.unitName"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" @click="dele(scope.$index)" size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <vxe-button @click="handleClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
@import url("/@/style/dialog.css");
</style>
<style>
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
